/**
  * 聊天组件代码。
  */

// 设置会话所属的视图
function setSessionView(view) {
    props.sessionView = view;

    messageListView.model = props.sessionView.sessionModel.loadMessages(-1, 50);

    messageListView.positionViewAtEnd();
}

// 发送文本消息
function sendTextMessage(messageModel){
    var content = messageInputArea.getText(0, messageInputArea.length).trim();
    if(content.length === 0){
        messageDialog.title = "发送消息";
        messageDialog.text = "消息内容不能为空";
        messageDialog.icon = MessageDialog.Information;

        messageDialog.visible = true;
        return;
    }

    sendMessage(content, X.Text);

    // scroll list view to the bottom
    messageInputArea.remove(0, messageInputArea.length);
}

// 发送图片消息
function sendImageMessage(imageUrl) {
    var content = imageUrl.trim();
    if(content.length === 0){
        messageDialog.title = "发送图片";
        messageDialog.text = "图片路径不能为空";
        messageDialog.icon = MessageDialog.Information;

        messageDialog.visible = true;
        return;
    }

    sendMessage(content, X.Image);
}

// 发送音频消息
function sendAudioMessage(fileUrl) {
    var content = fileUrl.trim();
    if(content.length === 0){
        messageDialog.title = "发送声音";
        messageDialog.text = "声音不能为空";
        messageDialog.icon = MessageDialog.Information;

        messageDialog.visible = true;
        return;
    }

    sendMessage(content, X.Audio);
}

// 发送视频消息
function sendVideoMessage(fileUrl) {
    var content = fileUrl.trim();
    if(content.length === 0){
        messageDialog.title = "发送视频";
        messageDialog.text = "视频不能为空";
        messageDialog.icon = MessageDialog.Information;

        messageDialog.visible = true;
        return;
    }

    sendMessage(content, X.Video);
}

// 发送名片消息
function sendVCardMessage(){
    sendMessage(content, X.VCard);
}

// 通用消息发送接口
function sendMessage(content, contentType) {
    //console.debug("content", content);
    props.sessionView.sendMessage(content, contentType)
}

//--------------------------------------------
// 事件处理
//--------------------------------------------

// 消息双击事件处理器
function onMessageDoubleClicked(content, contentType){
    switch(contentType){
    case X.Text:
        appendMessageToInputArea(content);
        break;

    case X.Image:
        showImage(content);
        break;

    default:
        break;
    }
}

// 向消息输入区追加消息
function appendMessageToInputArea(content) {
    messageInputArea.append(content);
}

// 打开图片
function showImage(fileUrl){
    var component = Qt.createComponent("../../qml/dialog/ImageViewerDialog.qml");
    if (component.status == Component.Ready){
        var window = component.createObject(chattingWidget, {imageSource: fileUrl});
        window.show();
    } else {
        console.error("Open image failed: ", component.errorString());
    }
}
